<template>
    <!-- 顶部 -->
    <div class="title">
      <span>商品搜索:</span>
      <a-input
        class="titleInput"
        v-model:value="value"
        placeholder="请输入"
        style="height: 5vh"
        allowClear
      />
      <a-button
        type="primary"
        style="height: 5vh; border-radius: 5px"
        @click="search"
        ><search-outlined />查询</a-button
      >
    </div>
    <!-- 主体显示 -->
    <div class="border">
      <!-- 添加按钮 -->
      <a-button
        type="link"
        style="
          color: #fff;
          height: 5vh;
          background-image: linear-gradient(-60deg, #ff5858 0%, #f09819 100%);
        "
        @click="showModal"
      >
        <template #icon><PlusCircleOutlined /></template>
        新建
      </a-button>
      <!-- 导入文件按钮 -->
      <span style="margin-left: 1vw">
        <a-button
          type="text"
          @click="addMany"
          style="height: 5vh; background-color: #fbf4f0"
        >
          导入数据
        </a-button>
      </span>
      <!-- 表格主体 -->
      <div class="tab">
        <a-table
          :columns="columns"
          :data-source="data"
          :pagination="false"
          :rowKey="unkey"
        >
          <!-- recocrd为当前数据 -->
          <template #shopimg="{ record }">
            <!-- 头像 图片 -->
            <a-avatar size="small" :src="record.img" />
          </template>
          <!-- 修改操作 -->
          <template #bodvCell="{ record }">
            <a style="margin-right: 0.5vw" @click="showModal2(record)">修改</a>
          </template>
        </a-table>
        <!-- 分页 -->
        <div style="margin-top: 4vh; margin-bottom: 4vh">
          <span style="color: #dbe5ef; font-size: 1rem; margin-left: 1rem">
            共{{ total }}条记录&nbsp;&nbsp;第 {{ current }}/{{
              Math.ceil(total / pageSize)
            }}页
          </span>
          <span style="float: right">
            <span style="margin-right: 3vw">
              <a-button
                style="background: #d5ddf8"
                :disabled="current <= 1"
                @click="onup"
                >上一页</a-button
              >
            </span>
            <span style="margin-right: 4vw">
              <a-button
                style="background: #d5ddf8"
                :disabled="current >= Math.ceil(total / pageSize)"
                @click="ondown"
                >下一页</a-button
              >
            </span>
          </span>
        </div>
        <!-- 模态框 -->
        <div>
          <!-- 添加的模态框 -->
          <a-modal
            v-model:visible="visible"
            title="新增商品"
            :footer="null"
            width="40vw"
            style="margin-top: -7vh"
          >
            <a-form
              ref="formRef"
              :model="formState"
              :rules="rules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-form-item label="商品名称:" name="name">
                <a-input
                  v-model:value="formState.name"
                  placeholder="请输入"
                  style="width: 23vw"
                />
              </a-form-item>
              <a-form-item label="品牌:" name="pp">
                <a-input
                  v-model:value="formState.pp"
                  placeholder="请输入"
                  style="width: 23vw"
                />
              </a-form-item>
              <a-form-item label="商品价格(元):" name="price">
                <a-input-number
                  :min="0"
                  placeholder="请输入"
                  v-model:value="formState.price"
                  style="width: 23vw; text-align: center"
                />
              </a-form-item>
              <a-form-item label="商品类型:" name="lx">
                <a-select
                  v-model:value="formState.lx"
                  placeholder="请选择"
                  style="width: 23vw; height: 5vh"
                  allowClear
                >
                  <a-select-option
                    v-for="(item, index) in data1"
                    :key="index"
                    :value="item._id"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="规格:" name="gg">
                <a-input
                  placeholder="请输入"
                  v-model:value="formState.gg"
                  style="width: 23vw"
                />
              </a-form-item>
              <!-- 图片上传，没有写 -->
              <a-form-item label="商品图片:" name="img">
                <!-- <a-input v-model:value="formState.img" style="width: 18vw" /> -->
                <a-upload
                  v-model:file-list="fileList1"
                  name="avatar"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  action="http://localhost:3201/api/shop/img"
                  :before-upload="beforeUpload"
                  @change="handleChange1"
                >
                  <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 6vw;height: 12vh;"/>
                  <div v-else>
                    <loading-outlined v-if="loading"></loading-outlined>
                    <plus-outlined v-else></plus-outlined>
                    <div class="ant-upload-text">Upload</div>
                  </div>
                </a-upload>
                <p style="color: #c2c8d3">
                  支持扩展名：jpg、png，文件不得大于100kb
                </p>
              </a-form-item>
              <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
                <a-button
                  style="
                    margin-right: 2vw;
                    background: #fbf4f0;
                    border: 0;
                    width: 5vw;
                  "
                  @click="handleQx"
                  >取消</a-button
                >
                <a-button
                  style="
                    margin-left: 2vw;
                    background-image: linear-gradient(
                      -60deg,
                      #ff5858 0%,
                      #f09819 100%
                    );
                    border: 0;
                    width: 5vw;
                    color: #fff;
                  "
                  @click="onSubmit"
                  >确定</a-button
                >
              </a-form-item>
            </a-form>
          </a-modal>
          <!-- 修改的模态框 -->
          <a-modal
            v-model:visible="visible2"
            title="修改商品"
            :footer="null"
            width="40vw"
            style="margin-top: -7vh"
          >
            <a-form
              ref="formRef"
              :model="seleone"
              :rules="rules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-form-item label="商品名称:" name="name">
                <a-input
                  v-model:value="seleone.name"
                  placeholder="请输入"
                  style="width: 23vw"
                />
              </a-form-item>
              <a-form-item label="品牌:" name="pp">
                <a-input
                  v-model:value="seleone.pp"
                  placeholder="请输入"
                  style="width: 23vw"
                />
              </a-form-item>
              <a-form-item label="商品价格(元):" name="price">
                <a-input-number
                  :min="0"
                  placeholder="请输入"
                  v-model:value="seleone.price"
                  style="width: 23vw; text-align: center"
                />
              </a-form-item>
              <a-form-item label="商品类型:" name="lx">
                <a-select
                  v-model:value="seleone.lx"
                  placeholder="请选择"
                  style="width: 23vw; height: 5vh"
                  allowClear
                >
                  <a-select-option
                    v-for="(item, index) in data1"
                    :key="index"
                    :value="item._id"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="规格:" name="gg">
                <a-input
                  placeholder="请输入"
                  v-model:value="seleone.gg"
                  style="width: 23vw"
                />
              </a-form-item>
              <!-- 图片上传，没有写 -->
              <a-form-item label="商品图片:" name="img">
                <!-- <a-input v-model:value="formState.img" style="width: 18vw" /> -->
                <a-upload
                  v-model:file-list="fileList2"
                  name="avatar"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  action="http://localhost:3201/api/shop/img"
                  :before-upload="beforeUpload2"
                  @change="handleChange2"
                >
                  <img v-if="imageUrl2" :src="imageUrl2" alt="avatar" style="width: 6vw;height: 12vh;"/>
                  <div v-else>
                    <loading-outlined v-if="loading2"></loading-outlined>
                    <plus-outlined v-else></plus-outlined>
                    <div class="ant-upload-text">Upload</div>
                  </div>
                </a-upload>
                <p style="color: #c2c8d3">
                  支持扩展名：jpg、png，文件不得大于100kb
                </p>
              </a-form-item>
              <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
                <a-button
                  style="
                    margin-right: 2vw;
                    background: #fbf4f0;
                    border: 0;
                    width: 5vw;
                  "
                  @click="handleQx2"
                  >取消</a-button
                >
                <a-button
                  style="
                    margin-left: 2vw;
                    background-image: linear-gradient(
                      -60deg,
                      #ff5858 0%,
                      #f09819 100%
                    );
                    border: 0;
                    width: 5vw;
                    color: #fff;
                  "
                  @click="onSubmit2"
                  >确定</a-button
                >
              </a-form-item>
            </a-form>
          </a-modal>
        </div>
      </div>
      <a-modal v-model:visible="uploadForm.addManyModal" title="数据导入">
        <a-upload
          v-model:file-list="fileList"
          name="file"
          :multiple="true"
          action="http://localhost:3201/api/cateFile"
          :headers="headers"
          @change="handleChange"
        >
          <a-button style="background: #5f84ff; color: white">
            <upload-outlined></upload-outlined>
            上传文件
          </a-button>
          <p style="margin: 10px 0; color: #bcc2ce">
            支持扩展名：xls、xlsx，文件不得大于1M
          </p>
          <p style="margin: 10px 0">
            <a-button>取消</a-button>
            <a-button>确认</a-button>
          </p>
        </a-upload>
      </a-modal>
    </div>
  </template>
    
    <script   lang="ts">
  import { defineComponent, ref, reactive, toRaw, onMounted } from "vue";
  import {
    SearchOutlined,
    PlusCircleOutlined,
    UploadOutlined,
    PlusOutlined,
    LoadingOutlined,
  } from "@ant-design/icons-vue";
  import { message, UploadChangeParam, UploadProps } from "ant-design-vue";
  import axios from "axios";
  const columns = [
    {
      title: "序号",
      dataIndex: "_id",
    },
    {
      title: "商品名称",
      dataIndex: "name",
    },
    {
      title: "商品图片",
      dataIndex: "img",
      slots: {
        customRender: "shopimg",
      },
    },
    {
      title: "品牌",
      dataIndex: "pp",
    },
    {
      title: "规格",
      dataIndex: "gg",
    },
    {
      title: "商品价格",
      dataIndex: "price",
    },
    {
      title: "商品类型",
      dataIndex: "lx.name",
    },
    {
      title: "创建日期",
      dataIndex: "cjtime",
    },
    {
      title: "操作",
      dataIndex: "cz",
      // 设置插槽
      slots: {
        customRender: "bodvCell",
      },
    },
  ];
  function getBase64(img: Blob, callback: (base64Url: string) => void) {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result as string));
    reader.readAsDataURL(img);
  }
  export default defineComponent({
    components: {
      SearchOutlined,
      PlusCircleOutlined,
      UploadOutlined,
      message,
      PlusOutlined,
      LoadingOutlined,
    },
    setup() {
      const data = ref([
        {
          key: 1,
          _id: 1,
          // 名称
          name: `可口可乐`,
          // 图片
          img: "http://lkd2-java.itheima.net/image/product1.png",
          // 品牌
          pp: "可口可乐",
          // 规格
          gg: "550ML",
          // 价格
          price: "3",
          // 对应的  分类外键
          lx: { _id: 1, name: "饮料" },
          // 时间
          cjtime:
            `${new Date().getFullYear()}` +
            "." +
            `${
              new Date().getMonth() + 1 < 10
                ? "0" + (new Date().getMonth() + 1)
                : new Date().getMonth() + 1
            }` +
            "." +
            `${
              new Date().getDate() < 10
                ? "0" + new Date().getDate()
                : new Date().getDate()
            }` +
            " " +
            `${new Date().getHours()}` +
            ":" +
            `${
              new Date().getMinutes() < 10
                ? "0" + new Date().getMinutes()
                : new Date().getMinutes()
            }` +
            ":" +
            `${
              new Date().getSeconds() < 10
                ? "0" + new Date().getSeconds()
                : new Date().getSeconds()
            }`,
        },
      ]);
      // 搜索数据
      const value = ref("");
      // table的key
      const unkey = ref(1);
      // 添加和修改 中的 分类下拉框数据
      const data1 = ref([
        { _id: 1, name: "饮料" },
        { _id: 2, name: "电子产品" },
      ]);
      const current = ref<number>(1);
      // 每页条数
      const pageSize = ref(10);
      // 总数量
      const total = ref(48);
      // 上一页
      const onup = () => {
        current.value--;
        showList();
      };
      // 下一页
      const ondown = () => {
        current.value++;
        showList();
      };
      // 添加的模态框状态
      const visible = ref<boolean>(false);
      const visible2 = ref<boolean>(false);
      // 添加模态框方法
      const showModal = () => {
        visible.value = true;
      };
      const showModal2 = (val) => {
          seleone.value=JSON.parse(JSON.stringify(val))
          seleone.value.lx=JSON.parse(JSON.stringify(val)).lx._id
          console.log(toRaw(seleone.value))
          imageUrl2.value=JSON.parse(JSON.stringify(val)).img
          visible2.value = true;
      };
      // 取消按钮
      const handleQx = () => {
        visible.value = false;
      };
      const handleQx2 = () => {
        visible2.value = false;
      };
      // 用于获取点击修改后的当前点击的数据
      const seleone = ref({});
      // 添加模态框的 表单数据
      let formState = reactive({
        name: "",
        img: "",
        lx: undefined,
        gg: "",
        price: undefined,
        pp: "",
        cjtime:
          `${new Date().getFullYear()}` +
          "." +
          `${
            new Date().getMonth() + 1 < 10
              ? "0" + (new Date().getMonth() + 1)
              : new Date().getMonth() + 1
          }` +
          "." +
          `${
            new Date().getDate() < 10
              ? "0" + new Date().getDate()
              : new Date().getDate()
          }` +
          " " +
          `${new Date().getHours()}` +
          ":" +
          `${
            new Date().getMinutes() < 10
              ? "0" + new Date().getMinutes()
              : new Date().getMinutes()
          }` +
          ":" +
          `${
            new Date().getSeconds() < 10
              ? "0" + new Date().getSeconds()
              : new Date().getSeconds()
          }`,
      });
      // 添加模态框的验证规则
      const rules = {
        name: [
          { required: true, message: "请输入", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "Length should be 1 to 15",
            trigger: "blur",
          },
        ],
        pp: [
          { required: true, message: "请输入", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "Length should be 1 to 10",
            trigger: "blur",
          },
        ],
        price: [
          { required: false },
          {
            pattern: /^[0-9]/,
            message: "不能小于0",
            trigger: ["change", "blur"],
          },
        ],
        lx: [{ required: true, message: "请输入", trigger: "blur" }],
        gg: [
          { required: true, message: "请输入", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "Length should be 1 to 10",
            trigger: "blur",
          },
        ],
        img: [{ required: true, message: "请输入", trigger: "blur" }],
      };
      const formRef = ref();
      // 添加模态框的确定事件
      const onSubmit = async () => {
        let baseurl = "http://localhost:3201/api";
        let { data } = await axios.post(`${baseurl}/shop/add`, formState);
        showList();
        visible.value=false
        return message.success(data.msg);
      };
      const onSubmit2 = async () => {
        let baseurl = "http://localhost:3201/api";
        console.log(toRaw(seleone.value))
        let { data } = await axios.put(`${baseurl}/shop/upde?_id=${seleone.value._id}`, toRaw(seleone.value));
        showList();
        visible2.value=false
        return message.success(data.msg);
      };
      const resetForm = () => {
        formRef.value.resetFields();
      };
      // 初始化事件
      onMounted(() => {
        // 获取商品分类所有数据 主要用于下拉框
        showLis();
        // 用于获取商品数据，加分页和搜索
        showList();
      });
      const showList = async () => {
        await axios
          .get(
            `http://localhost:3201/api/shop/list?pageSize=${pageSize.value}&pageIndex=${current.value}&seachname=${value.value}`
          )
          .then((res) => {
            data.value = res.data.data;
            total.value = res.data.count;
          });
      };
      // 搜索
      const search = () => {
        showList();
      };
      const showLis = async () => {
        await axios
          .get(`http://localhost:3201/api/shopfl/list?seachname=${value.value}`)
          .then((res) => {
            data1.value = res.data.data;
          });
      };
      //
      const qxsj = () => {
        formState.name = "";
      };
  
      let createManyCATE = async (path: any) => {
        let baseurl = "http://localhost:3201/api";
        let { data } = await axios.get(`${baseurl}/cate/addmany?path=${path}`);
        console.log(data);
        showList();
      };
  
      const handleChange = async (info: any) => {
        if (info.file.status !== "uploading") {
          console.log(info.file, info.fileList);
        }
  
        if (info.file.status === "done") {
          message.success(`${info.file.name} file uploaded successfully`);
          let path = info.file.response.path;
          createManyCATE(path);
        } else if (info.file.status === "error") {
          message.error(`${info.file.name} file upload failed.`);
        }
      };
  
      const fileList = ref([]);
  
      let uploadForm = reactive({
        addManyModal: false,
      });
      let addMany = async () => {
        uploadForm.addManyModal = true;
      };
      // 图片上传的数据
      const fileList1 = ref([]);
      const fileList2= ref([]);
      const loading = ref<boolean>(false);
      const loading2= ref<boolean>(false);
      const imageUrl = ref<string>("");
      const imageUrl2 = ref<string>("");
      const handleChange1 = (info: UploadChangeParam) => {
        console.log(info);
        if (info.file.status === "uploading") {
          loading.value = true;
          return;
        }
        if (info.file.status === "done") {
          // Get this url from response in real world.
  
          formState.img = info.file.response.path;
  
          getBase64(info.file.originFileObj, (base64Url: string) => {
            imageUrl.value = base64Url;
            loading.value = false;
          });
        }
        if (info.file.status === "error") {
          loading.value = false;
          message.error("upload error");
        }
      };
  
      const beforeUpload = (file: UploadProps["fileList"][number]) => {
        const isJpgOrPng =
          file.type === "image/jpeg" || file.type === "image/png";
        if (!isJpgOrPng) {
          message.error("You can only upload JPG file!");
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error("Image must smaller than 2MB!");
        }
        return isJpgOrPng && isLt2M;
      };
      const handleChange2 = (info: UploadChangeParam) => {
        console.log(info);
        if (info.file.status === "uploading") {
          loading2.value = true;
          return;
        }
        if (info.file.status === "done") {
          // Get this url from response in real world.
      
          seleone.value.img = info.file.response.path;
          console.log(seleone.value.img)
          getBase64(info.file.originFileObj, (base64Url: string) => {
            imageUrl2.value = base64Url;
            
            // seleone.value.img=base64Url
            loading2.value = false;
          });
        }
        if (info.file.status === "error") {
          loading2.value = false;
          message.error("upload error");
        }
      };
      
      const beforeUpload2 = (file: UploadProps["fileList"][number]) => {
        const isJpgOrPng =
          file.type === "image/jpeg" || file.type === "image/png";
        if (!isJpgOrPng) {
          message.error("You can only upload JPG file!");
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error("Image must smaller than 2MB!");
        }
        return isJpgOrPng && isLt2M;
      };
      return {
        data1,
        search,
        data,
        value,
        columns,
        current,
        pageSize,
        total,
        onup,
        ondown,
        labelCol: { span: 6 },
        wrapperCol: { span: 17 },
        unkey,
        visible,
        showModal,
        handleQx,
        seleone,
        rules,
        formRef,
        onSubmit,
        resetForm,
        qxsj,
        formState,
        addMany,
  
        //   文件上传浮框
        uploadForm,
        handleChange,
        fileList,
        headers: {
          authorization: localStorage.getItem("token"),
        },
  
        fileList1,
        loading,
        imageUrl,
        handleChange1,
        beforeUpload,
        // 修改
        visible2,
        showModal2,
        handleQx2,
        onSubmit2,
        fileList2,
        loading2,
        imageUrl2,
        handleChange2,
        beforeUpload2,
      };
    },
  });
  </script>
    
    <style scoped lang='scss'>
  .title {
    // 顶部搜索框
    height: 8vh;
    width: 82vw;
    background-color: #fff;
    line-height: 8vh;
    padding-left: 20px;
    .titleInput {
      width: 12vw;
      margin-left: 1vw;
      margin-right: 1vw;
    }
  }
  .border {
    // 内容主体
    width: 82vw;
    background-color: #fff;
    margin-top: 2vh;
    padding-top: 2vh;
    padding-bottom: 3vh;
    padding-left: 1vw;
    .plcz {
      background-color: rgb(251, 244, 240);
      margin-left: 10px;
    }
    .tab {
      // 表格
      margin-top: 2vh;
    }
  }
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
  
  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  </style>
    